﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SecureCommander.Helper;
using SecureCommander.Core.UserManagement;
using SecureCommander.Core.SecurityManager;

namespace SecureCommander.GUI
{
    /// <summary>
    /// Interaction logic for FormLogin.xaml
    /// </summary>
    public partial class FormLogin : Window
    {
        public List<UserInfo> Users { get; set; }
        public UserInfo LoginedUser { get; set; }

        public FormLogin()
        {
            InitializeComponent();
        }
        
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            if (txtEmail.Text == "" || txtPassword.Password == "")
            {
                FileHelper.ShowMessage("Please enter email and password correctly!", MessageBoxImage.Error);
                return;
            }

            UserInfo user = FindUser();
            if (user == null)
            {
                FileHelper.ShowMessage("Email invalid or not exists! Please try again.", MessageBoxImage.Error);
                return;
            }

            HashAlg hash = new HashAlg();
            if (user.Hash != hash.CreateHashFromPass_Salt(txtPassword.Password, user.Salt))
            {
                FileHelper.ShowMessage("Password invalid!", MessageBoxImage.Error);
                return;
            }

            LoginedUser = user;

            e.Handled = true;
            DialogResult = true;
            Close();
        }

        private UserInfo FindUser()
        {
            if (Users != null)
            {
                foreach (UserInfo user in Users)
                {
                    if (user.Mail == txtEmail.Text)
                    {
                        return user;
                    }
                }
            }

            return null;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            txtEmail.Focus();
        }
    }
}
